package com.app.actions.admin;

import com.app.SpringAnnotationDef;
import com.app.actions.BaseAction;
import com.app.model.*;
import com.app.service.admin.UserService;
import com.app.utils.PinyinUtil;
import com.opensymphony.xwork2.ActionSupport;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: mosg
 * Date: 12-3-3
 * Time: 下午9:46
 * To change this template use File | Settings | File Templates.
 */
@Scope(SpringAnnotationDef.SCOPE_PROTOTYPE)
@Component
@Namespace("/")
public class UserAction extends BaseAction {
    private static final Logger LOGGER = Logger.getLogger(UserAction.class);
    @Resource(name = SpringAnnotationDef.USER_SERVICE)
    private UserService service;


    private User user;

    private int logonType;    //登陆方式 1：用户名  2=邮箱  3=手机号码

    /**
     * 登陆的方法
     *
     * @return
     */
    @Action(value = "management", results = {@Result(name = SUCCESS, location = "/management/index/index.jsp"),
            @Result(name = "userList", location = "/admin/user/list.jsp"),
            @Result(name = "editPassWord", location = "/admin/user/editPassWord.jsp"),
            @Result(name = "logon", location = "/index.jsp"),
            @Result(name = "treeLookup", location = "/admin/user/treeLookup.jsp"),
            @Result(name = "addUser", location = "/admin/user/addUser.jsp")

    })
    public String management() {
        if (logonType > 0 && user != null && !"".equals(user.getUsername())) {
            User loginedUser = service.getDao().checkLogon(user, logonType);

            if (loginedUser == null) {
                //如果没找到当前仍，则看是不是admin 是的话就自动生成admin的帐号
                loginedUser = service.loadAdmin(user);
            }
            //放入到session
            if (loginedUser != null) {
                getSession(true).setAttribute("loginedUser", loginedUser);
            }
        }
        //如果什么数据都没有的话应该就是在首页刷新的，那么就去session中取值看看。
        user = getSessionLoginedUser();
        if (user != null) {
            //获取当前登录人的资源菜单
            List<ORG_Resources> resList = service.loadUserResources(user);
            //取得父节点               addresources
            List<ORG_Resources> parentRes = new ArrayList<ORG_Resources>();
            List<ORG_Resources> sonRes = new ArrayList<ORG_Resources>();
            for (ORG_Resources res : resList) {
                if (res.getParentId() == 0) {
                    parentRes.add(res);
                } else {
                    sonRes.add(res);
                }
            }
            getRequest().setAttribute("parentRes", parentRes);
            getRequest().setAttribute("sonRes", sonRes);
            getRequest().setAttribute("list", resList);

            LOGGER.info(user.getUsername() + "从首页登陆成功");
            return SUCCESS;
        }


        LOGGER.info("登陆失败!" + user);
        getRequest().setAttribute("msg", "用户名或者密码错误请重新登录!<br>测试阶段神账号：admin/admin");
        return "logon";
    }


    /**
     * 员工列表
     *
     * @return
     */
    public String getUserList() {
        List<User> list = service.getDao().listAll();
        getRequest().setAttribute("list", list);
        return "userList";
    }

    /**
     * 添加
     *
     * @return
     */
    public String toAdd() {

        //加载所有的用户组
        List<ORG_GorupManager> list = service.getGorupManagerDao().listAll();
        getRequest().setAttribute("list", list);

        if (user != null && user.getId() != null) {
            user = service.getDao().get(user.getId());
            getRequest().setAttribute("user", user);
        }
        return "addUser";
    }

    /**
     * 添加
     *
     * @return
     */
    public void addUser() {
        try {
            ORG_GorupManager gorupManager = service.getGorupManagerDao().get(Integer.parseInt(user.getPositionId()));
            user.setPositionName(gorupManager.getGorupName());

            String userName = PinyinUtil.getEname(user.getEname());
            user.setUsername(userName);

            boolean flag = false;
            if (user.getId() == null) {//如果是新增的用户初始化密码
                flag = true;
            }
            service.getDao().saveObject(user);

            if (flag) {
                ORG_UserInfo userInfo = new ORG_UserInfo();
                userInfo.setUserId(user.getId());
                userInfo.setUsername(userName);
                //TODO:以后可以在系统里面配置 现在暂时这样
                userInfo.setPassword("888888");
                userInfo.setStatus(0);//0 没登陆  1登陆
                userInfo.setCreateTimeStamp(new Date());
                userInfo.setPasswordUpdateTime(new Date());
                userInfo.setUpdateTimeStamp(new Date());
                service.getDao().saveObject(userInfo);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        /* if (user != null && user.getId() != null && user.getId() > 0) {
            service.getDao().update(user);
        } else {
            user.setStatus(0);
            service.getDao().save(user);
        }*/

        // JsonOut("添加成功", "userNav");
        setSort("3");
        JsonOut("添加成功");
    }

    public void deleteUser() {
        setSort("3");
        if (user != null && user.getId() != null && user.getId() > 0) {
            service.getDao().delete(user.getId());
            // JsonOut("添加成功", "userNav");
            JsonOut("添加成功");
        } else {
            //JsonOut("添加失败", "userNav");
            JsonOut("添加失败");
        }
    }


    public String editPassWord() {
        user = service.getDao().get(user.getId());
        getRequest().setAttribute("user", user);
        return "editPassWord";
    }

    public void updatePassWord() {
        User loginedUser = service.getDao().checkLogon(user, logonType);

        if (loginedUser == null) {
            JsonOut("密码错误，不能修改!");
            return;
        }
        ORG_UserInfo userInfo = service.getDao().getUserInfo(user.getId());
        if (userInfo != null) {
            String password = getRequest().getParameter("password");
            userInfo.setPassword(password);
            userInfo.setUpdateTimeStamp(new Date());
            service.getDao().saveObject(userInfo);
            JsonOut("恭喜您，修改成功！!");
        } else {
            JsonOut("密码错误，不能修改!");
        }

    }


    /**
     * 人的树形菜单
     *
     * @return
     */
    public String treeLookup() {

        String id = getRequest().getParameter("id");
        String name = getRequest().getParameter("name");

        getRequest().setAttribute("id", id);
        getRequest().setAttribute("name", name);

        List<ORG_GorupManager> list = service.getGorupManagerDao().listAll();
        getRequest().setAttribute("list", list);

        List<User> userList = service.getDao().listAll();
        getRequest().setAttribute("userList", userList);
        return "treeLookup";
    }


    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public int getLogonType() {
        return logonType;
    }

    public void setLogonType(int logonType) {
        this.logonType = logonType;
    }
}
